← Index
NYTProf Performance Profile   
For webmerge/scripts/webmerge.pl
  Run on Mon Oct 7 02:42:42 2013
Reported on Mon Oct 7 03:03:23 2013

Filename(eval 18)[/usr/lib64/perl5/vendor_perl/5.16.0/JSON.pm:268]
StatementsExecuted 20 statements in 6.18ms
Eval Invoked At/usr/lib64/perl5/vendor_perl/5.16.0/JSON.pm line 268
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
111135µs135µsJSON::Backend::XS::::init JSON::Backend::XS::init
11183µs350µsJSON::Backend::XS::::BEGIN@9 JSON::Backend::XS::BEGIN@9
11172µs151µsJSON::Backend::XS::::BEGIN@42 JSON::Backend::XS::BEGIN@42
11161µs138µsJSON::Backend::XS::Supportable::::BEGIN@99JSON::Backend::XS::Supportable::BEGIN@99
11160µs249µsJSON::Backend::XS::::BEGIN@11 JSON::Backend::XS::BEGIN@11
11155µs223µsJSON::Backend::XS::::BEGIN@18 JSON::Backend::XS::BEGIN@18
11154µs133µsJSON::Backend::XS::::BEGIN@29 JSON::Backend::XS::BEGIN@29
0000s0sJSON::Backend::XS::Supportable::::__ANON__[:110]JSON::Backend::XS::Supportable::__ANON__[:110]
0000s0sJSON::Backend::XS::Supportable::::__ANON__[:114]JSON::Backend::XS::Supportable::__ANON__[:114]
0000s0sJSON::Backend::XS::Supportable::::_decodeJSON::Backend::XS::Supportable::_decode
0000s0sJSON::Backend::XS::Supportable::::_encodeJSON::Backend::XS::Supportable::_encode
0000s0sJSON::Backend::XS::Supportable::::_incr_parseJSON::Backend::XS::Supportable::_incr_parse
0000s0sJSON::Backend::XS::Supportable::::_make_unsupported_methodJSON::Backend::XS::Supportable::_make_unsupported_method
0000s0sJSON::Backend::XS::Supportable::::_set_for_ppJSON::Backend::XS::Supportable::_set_for_pp
0000s0sJSON::Backend::XS::Supportable::::decode_prefixJSON::Backend::XS::Supportable::decode_prefix
0000s0sJSON::Backend::XS::Supportable::::get_indent_lengthJSON::Backend::XS::Supportable::get_indent_length
0000s0sJSON::Backend::XS::Supportable::::indent_lengthJSON::Backend::XS::Supportable::indent_length
0000s0sJSON::Backend::XS::::__ANON__[:32] JSON::Backend::XS::__ANON__[:32]
0000s0sJSON::Backend::XS::::__ANON__[:33] JSON::Backend::XS::__ANON__[:33]
0000s0sJSON::Backend::XS::::__ANON__[:63] JSON::Backend::XS::__ANON__[:63]
0000s0sJSON::Backend::XS::::support_by_pp JSON::Backend::XS::support_by_pp
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1
2
3#
4# Helper classes for Backend Module (XS)
5#
6
7package JSON::Backend::XS;
8
92240µs2618µs
# spent 350µs (83+267) within JSON::Backend::XS::BEGIN@9 which was called: # once (83µs+267µs) by JSON::_load_xs at line 9
use constant INDENT_LENGTH_FLAG => 15 << 12;
# spent 350µs making 1 call to JSON::Backend::XS::BEGIN@9 # spent 267µs making 1 call to constant::import
10
11141µs1190µs
# spent 249µs (60+190) within JSON::Backend::XS::BEGIN@11 which was called: # once (60µs+190µs) by JSON::_load_xs at line 16
use constant UNSUPPORTED_ENCODE_FLAG => {
# spent 190µs making 1 call to constant::import
12 ESCAPE_SLASH => 0x00000010,
13 ALLOW_BIGNUM => 0x00000020,
14 AS_NONBLESSED => 0x00000040,
15 EXPANDED => 0x10000000, # for developer's
161140µs1249µs};
# spent 249µs making 1 call to JSON::Backend::XS::BEGIN@11
17
18140µs1168µs
# spent 223µs (55+168) within JSON::Backend::XS::BEGIN@18 which was called: # once (55µs+168µs) by JSON::_load_xs at line 24
use constant UNSUPPORTED_DECODE_FLAG => {
# spent 168µs making 1 call to constant::import
19 LOOSE => 0x00000001,
20 ALLOW_BIGNUM => 0x00000002,
21 ALLOW_BAREKEY => 0x00000004,
22 ALLOW_SINGLEQUOTE => 0x00000008,
23 EXPANDED => 0x20000000, # for developer's
241260µs1223µs};
# spent 223µs making 1 call to JSON::Backend::XS::BEGIN@18
25
26
27
# spent 135µs within JSON::Backend::XS::init which was called: # once (135µs+0s) by JSON::_load_xs at line 269 of JSON.pm
sub init {
28111µs local $^W;
292743µs2212µs
# spent 133µs (54+79) within JSON::Backend::XS::BEGIN@29 which was called: # once (54µs+79µs) by JSON::_load_xs at line 29
no strict qw(refs);
# spent 133µs making 1 call to JSON::Backend::XS::BEGIN@29 # spent 79µs making 1 call to strict::unimport
30122µs *{"JSON::decode_json"} = \&{"JSON::XS::decode_json"};
31112µs *{"JSON::encode_json"} = \&{"JSON::XS::encode_json"};
32127µs *{"JSON::XS::is_xs"} = sub { 1 };
33143µs *{"JSON::XS::is_pp"} = sub { 0 };
34141µs return 1;
35}
36
37
38sub support_by_pp {
39 my ($class, @methods) = @_;
40
41 local $^W;
4221.42ms2230µs
# spent 151µs (72+79) within JSON::Backend::XS::BEGIN@42 which was called: # once (72µs+79µs) by JSON::_load_xs at line 42
no strict qw(refs);
# spent 151µs making 1 call to JSON::Backend::XS::BEGIN@42 # spent 79µs making 1 call to strict::unimport
43
44 my $JSON_XS_encode_orignal = \&JSON::XS::encode;
45 my $JSON_XS_decode_orignal = \&JSON::XS::decode;
46 my $JSON_XS_incr_parse_orignal = \&JSON::XS::incr_parse;
47
48 *JSON::XS::decode = \&JSON::Backend::XS::Supportable::_decode;
49 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
50 *JSON::XS::incr_parse = \&JSON::Backend::XS::Supportable::_incr_parse;
51
52 *{JSON::XS::_original_decode} = $JSON_XS_decode_orignal;
53 *{JSON::XS::_original_encode} = $JSON_XS_encode_orignal;
54 *{JSON::XS::_original_incr_parse} = $JSON_XS_incr_parse_orignal;
55
56 push @JSON::Backend::XS::Supportable::ISA, 'JSON';
57
58 my $pkg = 'JSON::Backend::XS::Supportable';
59
60 *{JSON::new} = sub {
61 my $proto = new JSON::XS; $$proto = 0;
62 bless $proto, $pkg;
63 };
64
65
66 for my $method (@methods) {
67 my $flag = uc($method);
68 my $type |= (UNSUPPORTED_ENCODE_FLAG->{$flag} || 0);
69 $type |= (UNSUPPORTED_DECODE_FLAG->{$flag} || 0);
70
71 next unless($type);
72
73 $pkg->_make_unsupported_method($method => $type);
74 }
75
76 push @{"JSON::XS::Boolean::ISA"}, qw(JSON::PP::Boolean);
77 push @{"JSON::PP::Boolean::ISA"}, qw(JSON::Boolean);
78
79 $JSON::DEBUG and Carp::carp("set -support_by_pp mode.");
80
81 return 1;
82}
83
- -
87#
88# Helper classes for XS
89#
90
91package JSON::Backend::XS::Supportable;
92
9316µs$Carp::Internal{'JSON::Backend::XS::Supportable'} = 1;
94
95sub _make_unsupported_method {
96 my ($pkg, $method, $type) = @_;
97
98 local $^W;
9923.13ms2216µs
# spent 138µs (61+78) within JSON::Backend::XS::Supportable::BEGIN@99 which was called: # once (61µs+78µs) by JSON::_load_xs at line 99
no strict qw(refs);
# spent 138µs making 1 call to JSON::Backend::XS::Supportable::BEGIN@99 # spent 78µs making 1 call to strict::unimport
100
101 *{"$pkg\::$method"} = sub {
102 local $^W;
103 if (defined $_[1] ? $_[1] : 1) {
104 ${$_[0]} |= $type;
105 }
106 else {
107 ${$_[0]} &= ~$type;
108 }
109 $_[0];
110 };
111
112 *{"$pkg\::get_$method"} = sub {
113 ${$_[0]} & $type ? 1 : '';
114 };
115
116}
117
118
119sub _set_for_pp {
120 JSON::_load_pp( $_INSTALL_ONLY );
121
122 my $type = shift;
123 my $pp = new JSON::PP;
124 my $prop = $_[0]->property;
125
126 for my $name (keys %$prop) {
127 $pp->$name( $prop->{$name} ? $prop->{$name} : 0 );
128 }
129
130 my $unsupported = $type eq 'encode' ? JSON::Backend::XS::UNSUPPORTED_ENCODE_FLAG
131 : JSON::Backend::XS::UNSUPPORTED_DECODE_FLAG;
132 my $flags = ${$_[0]} || 0;
133
134 for my $name (keys %$unsupported) {
135 next if ($name eq 'EXPANDED'); # for developer's
136 my $enable = ($flags & $unsupported->{$name}) ? 1 : 0;
137 my $method = lc $name;
138 $pp->$method($enable);
139 }
140
141 $pp->indent_length( $_[0]->get_indent_length );
142
143 return $pp;
144}
145
146sub _encode { # using with PP encod
147 if (${$_[0]}) {
148 _set_for_pp('encode' => @_)->encode($_[1]);
149 }
150 else {
151 $_[0]->_original_encode( $_[1] );
152 }
153}
154
155
156sub _decode { # if unsupported-flag is set, use PP
157 if (${$_[0]}) {
158 _set_for_pp('decode' => @_)->decode($_[1]);
159 }
160 else {
161 $_[0]->_original_decode( $_[1] );
162 }
163}
164
165
166sub decode_prefix { # if unsupported-flag is set, use PP
167 _set_for_pp('decode' => @_)->decode_prefix($_[1]);
168}
169
170
171sub _incr_parse {
172 if (${$_[0]}) {
173 _set_for_pp('decode' => @_)->incr_parse($_[1]);
174 }
175 else {
176 $_[0]->_original_incr_parse( $_[1] );
177 }
178}
179
180
181sub get_indent_length {
182 ${$_[0]} << 4 >> 16;
183}
184
185
186sub indent_length {
187 my $length = $_[1];
188
189 if (!defined $length or $length > 15 or $length < 0) {
190 Carp::carp "The acceptable range of indent_length() is 0 to 15.";
191 }
192 else {
193 local $^W;
194 $length <<= 12;
195 ${$_[0]} &= ~ JSON::Backend::XS::INDENT_LENGTH_FLAG;
196 ${$_[0]} |= $length;
197 *JSON::XS::encode = \&JSON::Backend::XS::Supportable::_encode;
198 }
199
200 $_[0];
201}
202
203
204113µs1;
205__END__
206
207=head1 NAME
208
209JSON - JSON (JavaScript Object Notation) encoder/decoder
210
211=head1 SYNOPSIS
212
213 use JSON; # imports encode_json, decode_json, to_json and from_json.
214
215 # simple and fast interfaces (expect/generate UTF-8)
216
217 $utf8_encoded_json_text = encode_json $perl_hash_or_arrayref;
218 $perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;
219
220 # OO-interface
221
222 $json = JSON->new->allow_nonref;
223
224 $json_text = $json->encode( $perl_scalar );
225 $perl_scalar = $json->decode( $json_text );
226
227 $pretty_printed = $json->pretty->encode( $perl_scalar ); # pretty-printing
228
229 # If you want to use PP only support features, call with '-support_by_pp'
230 # When XS unsupported feature is enable, using PP (de|en)code instead of XS ones.
231
232 use JSON -support_by_pp;
233
234 # option-acceptable interfaces (expect/generate UNICODE by default)
235
236 $json_text = to_json( $perl_scalar, { ascii => 1, pretty => 1 } );
237 $perl_scalar = from_json( $json_text, { utf8 => 1 } );
238
239 # Between (en|de)code_json and (to|from)_json, if you want to write
240 # a code which communicates to an outer world (encoded in UTF-8),
241 # recommend to use (en|de)code_json.
242
243=head1 VERSION
244
245 2.53
246
247This version is compatible with JSON::XS B<2.27> and later.
248
249
250=head1 NOTE
251
252JSON::PP was inculded in C<JSON> distribution.
253It comes to be a perl core module in Perl 5.14.
254And L<JSON::PP> will be split away it.
255
256C<JSON> distribution will inculde yet another JSON::PP modules.
257They are JSNO::backportPP and so on. JSON.pm should work as it did at all.
258
259=head1 DESCRIPTION
260
261 ************************** CAUTION ********************************
262 * This is 'JSON module version 2' and there are many differences *
263 * to version 1.xx *
264 * Please check your applications useing old version. *
265 * See to 'INCOMPATIBLE CHANGES TO OLD VERSION' *
266 *******************************************************************
267
268JSON (JavaScript Object Notation) is a simple data format.
269See to L<http://www.json.org/> and C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>).
270
271This module converts Perl data structures to JSON and vice versa using either
272L<JSON::XS> or L<JSON::PP>.
273
274JSON::XS is the fastest and most proper JSON module on CPAN which must be
275compiled and installed in your environment.
276JSON::PP is a pure-Perl module which is bundled in this distribution and
277has a strong compatibility to JSON::XS.
278
279This module try to use JSON::XS by default and fail to it, use JSON::PP instead.
280So its features completely depend on JSON::XS or JSON::PP.
281
282See to L<BACKEND MODULE DECISION>.
283
284To distinguish the module name 'JSON' and the format type JSON,
285the former is quoted by CE<lt>E<gt> (its results vary with your using media),
286and the latter is left just as it is.
287
288Module name : C<JSON>
289
290Format type : JSON
291
292=head2 FEATURES
293
294=over
295
296=item * correct unicode handling
297
298This module (i.e. backend modules) knows how to handle Unicode, documents
299how and when it does so, and even documents what "correct" means.
300
301Even though there are limitations, this feature is available since Perl version 5.6.
302
303JSON::XS requires Perl 5.8.2 (but works correctly in 5.8.8 or later), so in older versions
304C<JSON> sholud call JSON::PP as the backend which can be used since Perl 5.005.
305
306With Perl 5.8.x JSON::PP works, but from 5.8.0 to 5.8.2, because of a Perl side problem,
307JSON::PP works slower in the versions. And in 5.005, the Unicode handling is not available.
308See to L<JSON::PP/UNICODE HANDLING ON PERLS> for more information.
309
310See also to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>
311and L<JSON::XS/ENCODING/CODESET_FLAG_NOTES>.
312
313
314=item * round-trip integrity
315
316When you serialise a perl data structure using only data types supported
317by JSON and Perl, the deserialised data structure is identical on the Perl
318level. (e.g. the string "2.0" doesn't suddenly become "2" just because
319it looks like a number). There I<are> minor exceptions to this, read the
320L</MAPPING> section below to learn about those.
321
322
323=item * strict checking of JSON correctness
324
325There is no guessing, no generating of illegal JSON texts by default,
326and only JSON is accepted as input by default (the latter is a security
327feature).
328
329See to L<JSON::XS/FEATURES> and L<JSON::PP/FEATURES>.
330
331=item * fast
332
333This module returns a JSON::XS object itself if available.
334Compared to other JSON modules and other serialisers such as Storable,
335JSON::XS usually compares favourably in terms of speed, too.
336
337If not available, C<JSON> returns a JSON::PP object instead of JSON::XS and
338it is very slow as pure-Perl.
339
340=item * simple to use
341
342This module has both a simple functional interface as well as an
343object oriented interface interface.
344
345=item * reasonably versatile output formats
346
347You can choose between the most compact guaranteed-single-line format possible
348(nice for simple line-based protocols), a pure-ASCII format (for when your transport
349is not 8-bit clean, still supports the whole Unicode range), or a pretty-printed
350format (for when you want to read that stuff). Or you can combine those features
351in whatever way you like.
352
353=back
354
355=head1 FUNCTIONAL INTERFACE
356
357Some documents are copied and modified from L<JSON::XS/FUNCTIONAL INTERFACE>.
358C<to_json> and C<from_json> are additional functions.
359
360=head2 encode_json
361
362 $json_text = encode_json $perl_scalar
363
364Converts the given Perl data structure to a UTF-8 encoded, binary string.
365
366This function call is functionally identical to:
367
368 $json_text = JSON->new->utf8->encode($perl_scalar)
369
370=head2 decode_json
371
372 $perl_scalar = decode_json $json_text
373
374The opposite of C<encode_json>: expects an UTF-8 (binary) string and tries
375to parse that as an UTF-8 encoded JSON text, returning the resulting
376reference.
377
378This function call is functionally identical to:
379
380 $perl_scalar = JSON->new->utf8->decode($json_text)
381
382
383=head2 to_json
384
385 $json_text = to_json($perl_scalar)
386
387Converts the given Perl data structure to a json string.
388
389This function call is functionally identical to:
390
391 $json_text = JSON->new->encode($perl_scalar)
392
393Takes a hash reference as the second.
394
395 $json_text = to_json($perl_scalar, $flag_hashref)
396
397So,
398
399 $json_text = to_json($perl_scalar, {utf8 => 1, pretty => 1})
400
401equivalent to:
402
403 $json_text = JSON->new->utf8(1)->pretty(1)->encode($perl_scalar)
404
405If you want to write a modern perl code which communicates to outer world,
406you should use C<encode_json> (supposed that JSON data are encoded in UTF-8).
407
408=head2 from_json
409
410 $perl_scalar = from_json($json_text)
411
412The opposite of C<to_json>: expects a json string and tries
413to parse it, returning the resulting reference.
414
415This function call is functionally identical to:
416
417 $perl_scalar = JSON->decode($json_text)
418
419Takes a hash reference as the second.
420
421 $perl_scalar = from_json($json_text, $flag_hashref)
422
423So,
424
425 $perl_scalar = from_json($json_text, {utf8 => 1})
426
427equivalent to:
428
429 $perl_scalar = JSON->new->utf8(1)->decode($json_text)
430
431If you want to write a modern perl code which communicates to outer world,
432you should use C<decode_json> (supposed that JSON data are encoded in UTF-8).
433
434=head2 JSON::is_bool
435
436 $is_boolean = JSON::is_bool($scalar)
437
438Returns true if the passed scalar represents either JSON::true or
439JSON::false, two constants that act like C<1> and C<0> respectively
440and are also used to represent JSON C<true> and C<false> in Perl strings.
441
442=head2 JSON::true
443
444Returns JSON true value which is blessed object.
445It C<isa> JSON::Boolean object.
446
447=head2 JSON::false
448
449Returns JSON false value which is blessed object.
450It C<isa> JSON::Boolean object.
451
452=head2 JSON::null
453
454Returns C<undef>.
455
456See L<MAPPING>, below, for more information on how JSON values are mapped to
457Perl.
458
459=head1 HOW DO I DECODE A DATA FROM OUTER AND ENCODE TO OUTER
460
461This section supposes that your perl vresion is 5.8 or later.
462
463If you know a JSON text from an outer world - a network, a file content, and so on,
464is encoded in UTF-8, you should use C<decode_json> or C<JSON> module object
465with C<utf8> enable. And the decoded result will contain UNICODE characters.
466
467 # from network
468 my $json = JSON->new->utf8;
469 my $json_text = CGI->new->param( 'json_data' );
470 my $perl_scalar = $json->decode( $json_text );
471
472 # from file content
473 local $/;
474 open( my $fh, '<', 'json.data' );
475 $json_text = <$fh>;
476 $perl_scalar = decode_json( $json_text );
477
478If an outer data is not encoded in UTF-8, firstly you should C<decode> it.
479
480 use Encode;
481 local $/;
482 open( my $fh, '<', 'json.data' );
483 my $encoding = 'cp932';
484 my $unicode_json_text = decode( $encoding, <$fh> ); # UNICODE
485
486 # or you can write the below code.
487 #
488 # open( my $fh, "<:encoding($encoding)", 'json.data' );
489 # $unicode_json_text = <$fh>;
490
491In this case, C<$unicode_json_text> is of course UNICODE string.
492So you B<cannot> use C<decode_json> nor C<JSON> module object with C<utf8> enable.
493Instead of them, you use C<JSON> module object with C<utf8> disable or C<from_json>.
494
495 $perl_scalar = $json->utf8(0)->decode( $unicode_json_text );
496 # or
497 $perl_scalar = from_json( $unicode_json_text );
498
499Or C<encode 'utf8'> and C<decode_json>:
500
501 $perl_scalar = decode_json( encode( 'utf8', $unicode_json_text ) );
502 # this way is not efficient.
503
504And now, you want to convert your C<$perl_scalar> into JSON data and
505send it to an outer world - a network or a file content, and so on.
506
507Your data usually contains UNICODE strings and you want the converted data to be encoded
508in UTF-8, you should use C<encode_json> or C<JSON> module object with C<utf8> enable.
509
510 print encode_json( $perl_scalar ); # to a network? file? or display?
511 # or
512 print $json->utf8->encode( $perl_scalar );
513
514If C<$perl_scalar> does not contain UNICODE but C<$encoding>-encoded strings
515for some reason, then its characters are regarded as B<latin1> for perl
516(because it does not concern with your $encoding).
517You B<cannot> use C<encode_json> nor C<JSON> module object with C<utf8> enable.
518Instead of them, you use C<JSON> module object with C<utf8> disable or C<to_json>.
519Note that the resulted text is a UNICODE string but no problem to print it.
520
521 # $perl_scalar contains $encoding encoded string values
522 $unicode_json_text = $json->utf8(0)->encode( $perl_scalar );
523 # or
524 $unicode_json_text = to_json( $perl_scalar );
525 # $unicode_json_text consists of characters less than 0x100
526 print $unicode_json_text;
527
528Or C<decode $encoding> all string values and C<encode_json>:
529
530 $perl_scalar->{ foo } = decode( $encoding, $perl_scalar->{ foo } );
531 # ... do it to each string values, then encode_json
532 $json_text = encode_json( $perl_scalar );
533
534This method is a proper way but probably not efficient.
535
536See to L<Encode>, L<perluniintro>.
537
538
539=head1 COMMON OBJECT-ORIENTED INTERFACE
540
541=head2 new
542
543 $json = new JSON
544
545Returns a new C<JSON> object inherited from either JSON::XS or JSON::PP
546that can be used to de/encode JSON strings.
547
548All boolean flags described below are by default I<disabled>.
549
550The mutators for flags all return the JSON object again and thus calls can
551be chained:
552
553 my $json = JSON->new->utf8->space_after->encode({a => [1,2]})
554 => {"a": [1, 2]}
555
556=head2 ascii
557
558 $json = $json->ascii([$enable])
559
560 $enabled = $json->get_ascii
561
562If $enable is true (or missing), then the encode method will not generate characters outside
563the code range 0..127. Any Unicode characters outside that range will be escaped using either
564a single \uXXXX or a double \uHHHH\uLLLLL escape sequence, as per RFC4627.
565
566If $enable is false, then the encode method will not escape Unicode characters unless
567required by the JSON syntax or other flags. This results in a faster and more compact format.
568
569This feature depends on the used Perl version and environment.
570
571See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
572
573 JSON->new->ascii(1)->encode([chr 0x10401])
574 => ["\ud801\udc01"]
575
576=head2 latin1
577
578 $json = $json->latin1([$enable])
579
580 $enabled = $json->get_latin1
581
582If $enable is true (or missing), then the encode method will encode the resulting JSON
583text as latin1 (or iso-8859-1), escaping any characters outside the code range 0..255.
584
585If $enable is false, then the encode method will not escape Unicode characters
586unless required by the JSON syntax or other flags.
587
588 JSON->new->latin1->encode (["\x{89}\x{abc}"]
589 => ["\x{89}\\u0abc"] # (perl syntax, U+abc escaped, U+89 not)
590
591=head2 utf8
592
593 $json = $json->utf8([$enable])
594
595 $enabled = $json->get_utf8
596
597If $enable is true (or missing), then the encode method will encode the JSON result
598into UTF-8, as required by many protocols, while the decode method expects to be handled
599an UTF-8-encoded string. Please note that UTF-8-encoded strings do not contain any
600characters outside the range 0..255, they are thus useful for bytewise/binary I/O.
601
602In future versions, enabling this option might enable autodetection of the UTF-16 and UTF-32
603encoding families, as described in RFC4627.
604
605If $enable is false, then the encode method will return the JSON string as a (non-encoded)
606Unicode string, while decode expects thus a Unicode string. Any decoding or encoding
607(e.g. to UTF-8 or UTF-16) needs to be done yourself, e.g. using the Encode module.
608
609
610Example, output UTF-16BE-encoded JSON:
611
612 use Encode;
613 $jsontext = encode "UTF-16BE", JSON::XS->new->encode ($object);
614
615Example, decode UTF-32LE-encoded JSON:
616
617 use Encode;
618 $object = JSON::XS->new->decode (decode "UTF-32LE", $jsontext);
619
620See to L<JSON::PP/UNICODE HANDLING ON PERLS> if the backend is PP.
621
622
623=head2 pretty
624
625 $json = $json->pretty([$enable])
626
627This enables (or disables) all of the C<indent>, C<space_before> and
628C<space_after> (and in the future possibly more) flags in one call to
629generate the most readable (or most compact) form possible.
630
631Equivalent to:
632
633 $json->indent->space_before->space_after
634
635The indent space length is three and JSON::XS cannot change the indent
636space length.
637
638=head2 indent
639
640 $json = $json->indent([$enable])
641
642 $enabled = $json->get_indent
643
644If C<$enable> is true (or missing), then the C<encode> method will use a multiline
645format as output, putting every array member or object/hash key-value pair
646into its own line, identing them properly.
647
648If C<$enable> is false, no newlines or indenting will be produced, and the
649resulting JSON text is guarenteed not to contain any C<newlines>.
650
651This setting has no effect when decoding JSON texts.
652
653The indent space length is three.
654With JSON::PP, you can also access C<indent_length> to change indent space length.
655
656
657=head2 space_before
658
659 $json = $json->space_before([$enable])
660
661 $enabled = $json->get_space_before
662
663If C<$enable> is true (or missing), then the C<encode> method will add an extra
664optional space before the C<:> separating keys from values in JSON objects.
665
666If C<$enable> is false, then the C<encode> method will not add any extra
667space at those places.
668
669This setting has no effect when decoding JSON texts.
670
671Example, space_before enabled, space_after and indent disabled:
672
673 {"key" :"value"}
674
675
676=head2 space_after
677
678 $json = $json->space_after([$enable])
679
680 $enabled = $json->get_space_after
681
682If C<$enable> is true (or missing), then the C<encode> method will add an extra
683optional space after the C<:> separating keys from values in JSON objects
684and extra whitespace after the C<,> separating key-value pairs and array
685members.
686
687If C<$enable> is false, then the C<encode> method will not add any extra
688space at those places.
689
690This setting has no effect when decoding JSON texts.
691
692Example, space_before and indent disabled, space_after enabled:
693
694 {"key": "value"}
695
696
697=head2 relaxed
698
699 $json = $json->relaxed([$enable])
700
701 $enabled = $json->get_relaxed
702
703If C<$enable> is true (or missing), then C<decode> will accept some
704extensions to normal JSON syntax (see below). C<encode> will not be
705affected in anyway. I<Be aware that this option makes you accept invalid
706JSON texts as if they were valid!>. I suggest only to use this option to
707parse application-specific files written by humans (configuration files,
708resource files etc.)
709
710If C<$enable> is false (the default), then C<decode> will only accept
711valid JSON texts.
712
713Currently accepted extensions are:
714
715=over 4
716
717=item * list items can have an end-comma
718
719JSON I<separates> array elements and key-value pairs with commas. This
720can be annoying if you write JSON texts manually and want to be able to
721quickly append elements, so this extension accepts comma at the end of
722such items not just between them:
723
724 [
725 1,
726 2, <- this comma not normally allowed
727 ]
728 {
729 "k1": "v1",
730 "k2": "v2", <- this comma not normally allowed
731 }
732
733=item * shell-style '#'-comments
734
735Whenever JSON allows whitespace, shell-style comments are additionally
736allowed. They are terminated by the first carriage-return or line-feed
737character, after which more white-space and comments are allowed.
738
739 [
740 1, # this comment not allowed in JSON
741 # neither this one...
742 ]
743
744=back
745
746
747=head2 canonical
748
749 $json = $json->canonical([$enable])
750
751 $enabled = $json->get_canonical
752
753If C<$enable> is true (or missing), then the C<encode> method will output JSON objects
754by sorting their keys. This is adding a comparatively high overhead.
755
756If C<$enable> is false, then the C<encode> method will output key-value
757pairs in the order Perl stores them (which will likely change between runs
758of the same script).
759
760This option is useful if you want the same data structure to be encoded as
761the same JSON text (given the same overall settings). If it is disabled,
762the same hash might be encoded differently even if contains the same data,
763as key-value pairs have no inherent ordering in Perl.
764
765This setting has no effect when decoding JSON texts.
766
767=head2 allow_nonref
768
769 $json = $json->allow_nonref([$enable])
770
771 $enabled = $json->get_allow_nonref
772
773If C<$enable> is true (or missing), then the C<encode> method can convert a
774non-reference into its corresponding string, number or null JSON value,
775which is an extension to RFC4627. Likewise, C<decode> will accept those JSON
776values instead of croaking.
777
778If C<$enable> is false, then the C<encode> method will croak if it isn't
779passed an arrayref or hashref, as JSON texts must either be an object
780or array. Likewise, C<decode> will croak if given something that is not a
781JSON object or array.
782
783 JSON->new->allow_nonref->encode ("Hello, World!")
784 => "Hello, World!"
785
786=head2 allow_unknown
787
788 $json = $json->allow_unknown ([$enable])
789
790 $enabled = $json->get_allow_unknown
791
792If $enable is true (or missing), then "encode" will *not* throw an
793exception when it encounters values it cannot represent in JSON (for
794example, filehandles) but instead will encode a JSON "null" value.
795Note that blessed objects are not included here and are handled
796separately by c<allow_nonref>.
797
798If $enable is false (the default), then "encode" will throw an
799exception when it encounters anything it cannot encode as JSON.
800
801This option does not affect "decode" in any way, and it is
802recommended to leave it off unless you know your communications
803partner.
804
805=head2 allow_blessed
806
807 $json = $json->allow_blessed([$enable])
808
809 $enabled = $json->get_allow_blessed
810
811If C<$enable> is true (or missing), then the C<encode> method will not
812barf when it encounters a blessed reference. Instead, the value of the
813B<convert_blessed> option will decide whether C<null> (C<convert_blessed>
814disabled or no C<TO_JSON> method found) or a representation of the
815object (C<convert_blessed> enabled and C<TO_JSON> method found) is being
816encoded. Has no effect on C<decode>.
817
818If C<$enable> is false (the default), then C<encode> will throw an
819exception when it encounters a blessed object.
820
821
822=head2 convert_blessed
823
824 $json = $json->convert_blessed([$enable])
825
826 $enabled = $json->get_convert_blessed
827
828If C<$enable> is true (or missing), then C<encode>, upon encountering a
829blessed object, will check for the availability of the C<TO_JSON> method
830on the object's class. If found, it will be called in scalar context
831and the resulting scalar will be encoded instead of the object. If no
832C<TO_JSON> method is found, the value of C<allow_blessed> will decide what
833to do.
834
835The C<TO_JSON> method may safely call die if it wants. If C<TO_JSON>
836returns other blessed objects, those will be handled in the same
837way. C<TO_JSON> must take care of not causing an endless recursion cycle
838(== crash) in this case. The name of C<TO_JSON> was chosen because other
839methods called by the Perl core (== not by the user of the object) are
840usually in upper case letters and to avoid collisions with the C<to_json>
841function or method.
842
843This setting does not yet influence C<decode> in any way.
844
845If C<$enable> is false, then the C<allow_blessed> setting will decide what
846to do when a blessed object is found.
847
848=over
849
850=item convert_blessed_universally mode
851
852If use C<JSON> with C<-convert_blessed_universally>, the C<UNIVERSAL::TO_JSON>
853subroutine is defined as the below code:
854
855 *UNIVERSAL::TO_JSON = sub {
856 my $b_obj = B::svref_2object( $_[0] );
857 return $b_obj->isa('B::HV') ? { %{ $_[0] } }
858 : $b_obj->isa('B::AV') ? [ @{ $_[0] } ]
859 : undef
860 ;
861 }
862
863This will cause that C<encode> method converts simple blessed objects into
864JSON objects as non-blessed object.
865
866 JSON -convert_blessed_universally;
867 $json->allow_blessed->convert_blessed->encode( $blessed_object )
868
869This feature is experimental and may be removed in the future.
870
871=back
872
873=head2 filter_json_object
874
875 $json = $json->filter_json_object([$coderef])
876
877When C<$coderef> is specified, it will be called from C<decode> each
878time it decodes a JSON object. The only argument passed to the coderef
879is a reference to the newly-created hash. If the code references returns
880a single scalar (which need not be a reference), this value
881(i.e. a copy of that scalar to avoid aliasing) is inserted into the
882deserialised data structure. If it returns an empty list
883(NOTE: I<not> C<undef>, which is a valid scalar), the original deserialised
884hash will be inserted. This setting can slow down decoding considerably.
885
886When C<$coderef> is omitted or undefined, any existing callback will
887be removed and C<decode> will not change the deserialised hash in any
888way.
889
890Example, convert all JSON objects into the integer 5:
891
892 my $js = JSON->new->filter_json_object (sub { 5 });
893 # returns [5]
894 $js->decode ('[{}]'); # the given subroutine takes a hash reference.
895 # throw an exception because allow_nonref is not enabled
896 # so a lone 5 is not allowed.
897 $js->decode ('{"a":1, "b":2}');
898
899
900=head2 filter_json_single_key_object
901
902 $json = $json->filter_json_single_key_object($key [=> $coderef])
903
904Works remotely similar to C<filter_json_object>, but is only called for
905JSON objects having a single key named C<$key>.
906
907This C<$coderef> is called before the one specified via
908C<filter_json_object>, if any. It gets passed the single value in the JSON
909object. If it returns a single value, it will be inserted into the data
910structure. If it returns nothing (not even C<undef> but the empty list),
911the callback from C<filter_json_object> will be called next, as if no
912single-key callback were specified.
913
914If C<$coderef> is omitted or undefined, the corresponding callback will be
915disabled. There can only ever be one callback for a given key.
916
917As this callback gets called less often then the C<filter_json_object>
918one, decoding speed will not usually suffer as much. Therefore, single-key
919objects make excellent targets to serialise Perl objects into, especially
920as single-key JSON objects are as close to the type-tagged value concept
921as JSON gets (it's basically an ID/VALUE tuple). Of course, JSON does not
922support this in any way, so you need to make sure your data never looks
923like a serialised Perl hash.
924
925Typical names for the single object key are C<__class_whatever__>, or
926C<$__dollars_are_rarely_used__$> or C<}ugly_brace_placement>, or even
927things like C<__class_md5sum(classname)__>, to reduce the risk of clashing
928with real hashes.
929
930Example, decode JSON objects of the form C<< { "__widget__" => <id> } >>
931into the corresponding C<< $WIDGET{<id>} >> object:
932
933 # return whatever is in $WIDGET{5}:
934 JSON
935 ->new
936 ->filter_json_single_key_object (__widget__ => sub {
937 $WIDGET{ $_[0] }
938 })
939 ->decode ('{"__widget__": 5')
940
941 # this can be used with a TO_JSON method in some "widget" class
942 # for serialisation to json:
943 sub WidgetBase::TO_JSON {
944 my ($self) = @_;
945
946 unless ($self->{id}) {
947 $self->{id} = ..get..some..id..;
948 $WIDGET{$self->{id}} = $self;
949 }
950
951 { __widget__ => $self->{id} }
952 }
953
954
955=head2 shrink
956
957 $json = $json->shrink([$enable])
958
959 $enabled = $json->get_shrink
960
961With JSON::XS, this flag resizes strings generated by either
962C<encode> or C<decode> to their minimum size possible. This can save
963memory when your JSON texts are either very very long or you have many
964short strings. It will also try to downgrade any strings to octet-form
965if possible: perl stores strings internally either in an encoding called
966UTF-X or in octet-form. The latter cannot store everything but uses less
967space in general (and some buggy Perl or C code might even rely on that
968internal representation being used).
969
970With JSON::PP, it is noop about resizing strings but tries
971C<utf8::downgrade> to the returned string by C<encode>. See to L<utf8>.
972
973See to L<JSON::XS/OBJECT-ORIENTED INTERFACE> and L<JSON::PP/METHODS>.
974
975=head2 max_depth
976
977 $json = $json->max_depth([$maximum_nesting_depth])
978
979 $max_depth = $json->get_max_depth
980
981Sets the maximum nesting level (default C<512>) accepted while encoding
982or decoding. If a higher nesting level is detected in JSON text or a Perl
983data structure, then the encoder and decoder will stop and croak at that
984point.
985
986Nesting level is defined by number of hash- or arrayrefs that the encoder
987needs to traverse to reach a given point or the number of C<{> or C<[>
988characters without their matching closing parenthesis crossed to reach a
989given character in a string.
990
991If no argument is given, the highest possible setting will be used, which
992is rarely useful.
993
994Note that nesting is implemented by recursion in C. The default value has
995been chosen to be as large as typical operating systems allow without
996crashing. (JSON::XS)
997
998With JSON::PP as the backend, when a large value (100 or more) was set and
999it de/encodes a deep nested object/text, it may raise a warning
1000'Deep recursion on subroutin' at the perl runtime phase.
1001
1002See L<JSON::XS/SECURITY CONSIDERATIONS> for more info on why this is useful.
1003
1004=head2 max_size
1005
1006 $json = $json->max_size([$maximum_string_size])
1007
1008 $max_size = $json->get_max_size
1009
1010Set the maximum length a JSON text may have (in bytes) where decoding is
1011being attempted. The default is C<0>, meaning no limit. When C<decode>
1012is called on a string that is longer then this many bytes, it will not
1013attempt to decode the string but throw an exception. This setting has no
1014effect on C<encode> (yet).
1015
1016If no argument is given, the limit check will be deactivated (same as when
1017C<0> is specified).
1018
1019See L<JSON::XS/SECURITY CONSIDERATIONS>, below, for more info on why this is useful.
1020
1021=head2 encode
1022
1023 $json_text = $json->encode($perl_scalar)
1024
1025Converts the given Perl data structure (a simple scalar or a reference
1026to a hash or array) to its JSON representation. Simple scalars will be
1027converted into JSON string or number sequences, while references to arrays
1028become JSON arrays and references to hashes become JSON objects. Undefined
1029Perl values (e.g. C<undef>) become JSON C<null> values.
1030References to the integers C<0> and C<1> are converted into C<true> and C<false>.
1031
1032=head2 decode
1033
1034 $perl_scalar = $json->decode($json_text)
1035
1036The opposite of C<encode>: expects a JSON text and tries to parse it,
1037returning the resulting simple scalar or reference. Croaks on error.
1038
1039JSON numbers and strings become simple Perl scalars. JSON arrays become
1040Perl arrayrefs and JSON objects become Perl hashrefs. C<true> becomes
1041C<1> (C<JSON::true>), C<false> becomes C<0> (C<JSON::false>) and
1042C<null> becomes C<undef>.
1043
1044=head2 decode_prefix
1045
1046 ($perl_scalar, $characters) = $json->decode_prefix($json_text)
1047
1048This works like the C<decode> method, but instead of raising an exception
1049when there is trailing garbage after the first JSON object, it will
1050silently stop parsing there and return the number of characters consumed
1051so far.
1052
1053 JSON->new->decode_prefix ("[1] the tail")
1054 => ([], 3)
1055
1056See to L<JSON::XS/OBJECT-ORIENTED INTERFACE>
1057
1058=head2 property
1059
1060 $boolean = $json->property($property_name)
1061
1062Returns a boolean value about above some properties.
1063
1064The available properties are C<ascii>, C<latin1>, C<utf8>,
1065C<indent>,C<space_before>, C<space_after>, C<relaxed>, C<canonical>,
1066C<allow_nonref>, C<allow_unknown>, C<allow_blessed>, C<convert_blessed>,
1067C<shrink>, C<max_depth> and C<max_size>.
1068
1069 $boolean = $json->property('utf8');
1070 => 0
1071 $json->utf8;
1072 $boolean = $json->property('utf8');
1073 => 1
1074
1075Sets the property with a given boolean value.
1076
1077 $json = $json->property($property_name => $boolean);
1078
1079With no argumnt, it returns all the above properties as a hash reference.
1080
1081 $flag_hashref = $json->property();
1082
1083=head1 INCREMENTAL PARSING
1084
1085Most of this section are copied and modified from L<JSON::XS/INCREMENTAL PARSING>.
1086
1087In some cases, there is the need for incremental parsing of JSON texts.
1088This module does allow you to parse a JSON stream incrementally.
1089It does so by accumulating text until it has a full JSON object, which
1090it then can decode. This process is similar to using C<decode_prefix>
1091to see if a full JSON object is available, but is much more efficient
1092(and can be implemented with a minimum of method calls).
1093
1094The backend module will only attempt to parse the JSON text once it is sure it
1095has enough text to get a decisive result, using a very simple but
1096truly incremental parser. This means that it sometimes won't stop as
1097early as the full parser, for example, it doesn't detect parenthese
1098mismatches. The only thing it guarantees is that it starts decoding as
1099soon as a syntactically valid JSON text has been seen. This means you need
1100to set resource limits (e.g. C<max_size>) to ensure the parser will stop
1101parsing in the presence if syntax errors.
1102
1103The following methods implement this incremental parser.
1104
1105=head2 incr_parse
1106
1107 $json->incr_parse( [$string] ) # void context
1108
1109 $obj_or_undef = $json->incr_parse( [$string] ) # scalar context
1110
1111 @obj_or_empty = $json->incr_parse( [$string] ) # list context
1112
1113This is the central parsing function. It can both append new text and
1114extract objects from the stream accumulated so far (both of these
1115functions are optional).
1116
1117If C<$string> is given, then this string is appended to the already
1118existing JSON fragment stored in the C<$json> object.
1119
1120After that, if the function is called in void context, it will simply
1121return without doing anything further. This can be used to add more text
1122in as many chunks as you want.
1123
1124If the method is called in scalar context, then it will try to extract
1125exactly I<one> JSON object. If that is successful, it will return this
1126object, otherwise it will return C<undef>. If there is a parse error,
1127this method will croak just as C<decode> would do (one can then use
1128C<incr_skip> to skip the errornous part). This is the most common way of
1129using the method.
1130
1131And finally, in list context, it will try to extract as many objects
1132from the stream as it can find and return them, or the empty list
1133otherwise. For this to work, there must be no separators between the JSON
1134objects or arrays, instead they must be concatenated back-to-back. If
1135an error occurs, an exception will be raised as in the scalar context
1136case. Note that in this case, any previously-parsed JSON texts will be
1137lost.
1138
1139Example: Parse some JSON arrays/objects in a given string and return them.
1140
1141 my @objs = JSON->new->incr_parse ("[5][7][1,2]");
1142
1143=head2 incr_text
1144
1145 $lvalue_string = $json->incr_text
1146
1147This method returns the currently stored JSON fragment as an lvalue, that
1148is, you can manipulate it. This I<only> works when a preceding call to
1149C<incr_parse> in I<scalar context> successfully returned an object. Under
1150all other circumstances you must not call this function (I mean it.
1151although in simple tests it might actually work, it I<will> fail under
1152real world conditions). As a special exception, you can also call this
1153method before having parsed anything.
1154
1155This function is useful in two cases: a) finding the trailing text after a
1156JSON object or b) parsing multiple JSON objects separated by non-JSON text
1157(such as commas).
1158
1159 $json->incr_text =~ s/\s*,\s*//;
1160
1161In Perl 5.005, C<lvalue> attribute is not available.
1162You must write codes like the below:
1163
1164 $string = $json->incr_text;
1165 $string =~ s/\s*,\s*//;
1166 $json->incr_text( $string );
1167
1168=head2 incr_skip
1169
1170 $json->incr_skip
1171
1172This will reset the state of the incremental parser and will remove the
1173parsed text from the input buffer. This is useful after C<incr_parse>
1174died, in which case the input buffer and incremental parser state is left
1175unchanged, to skip the text parsed so far and to reset the parse state.
1176
1177=head2 incr_reset
1178
1179 $json->incr_reset
1180
1181This completely resets the incremental parser, that is, after this call,
1182it will be as if the parser had never parsed anything.
1183
1184This is useful if you want ot repeatedly parse JSON objects and want to
1185ignore any trailing data, which means you have to reset the parser after
1186each successful decode.
1187
1188See to L<JSON::XS/INCREMENTAL PARSING> for examples.
1189
1190
1191=head1 JSON::PP SUPPORT METHODS
1192
1193The below methods are JSON::PP own methods, so when C<JSON> works
1194with JSON::PP (i.e. the created object is a JSON::PP object), available.
1195See to L<JSON::PP/JSON::PP OWN METHODS> in detail.
1196
1197If you use C<JSON> with additonal C<-support_by_pp>, some methods
1198are available even with JSON::XS. See to L<USE PP FEATURES EVEN THOUGH XS BACKEND>.
1199
1200 BEING { $ENV{PERL_JSON_BACKEND} = 'JSON::XS' }
1201
1202 use JSON -support_by_pp;
1203
1204 my $json = new JSON;
1205 $json->allow_nonref->escape_slash->encode("/");
1206
1207 # functional interfaces too.
1208 print to_json(["/"], {escape_slash => 1});
1209 print from_json('["foo"]', {utf8 => 1});
1210
1211If you do not want to all functions but C<-support_by_pp>,
1212use C<-no_export>.
1213
1214 use JSON -support_by_pp, -no_export;
1215 # functional interfaces are not exported.
1216
1217=head2 allow_singlequote
1218
1219 $json = $json->allow_singlequote([$enable])
1220
1221If C<$enable> is true (or missing), then C<decode> will accept
1222any JSON strings quoted by single quotations that are invalid JSON
1223format.
1224
1225 $json->allow_singlequote->decode({"foo":'bar'});
1226 $json->allow_singlequote->decode({'foo':"bar"});
1227 $json->allow_singlequote->decode({'foo':'bar'});
1228
1229As same as the C<relaxed> option, this option may be used to parse
1230application-specific files written by humans.
1231
1232=head2 allow_barekey
1233
1234 $json = $json->allow_barekey([$enable])
1235
1236If C<$enable> is true (or missing), then C<decode> will accept
1237bare keys of JSON object that are invalid JSON format.
1238
1239As same as the C<relaxed> option, this option may be used to parse
1240application-specific files written by humans.
1241
1242 $json->allow_barekey->decode('{foo:"bar"}');
1243
1244=head2 allow_bignum
1245
1246 $json = $json->allow_bignum([$enable])
1247
1248If C<$enable> is true (or missing), then C<decode> will convert
1249the big integer Perl cannot handle as integer into a L<Math::BigInt>
1250object and convert a floating number (any) into a L<Math::BigFloat>.
1251
1252On the contary, C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1253objects into JSON numbers with C<allow_blessed> enable.
1254
1255 $json->allow_nonref->allow_blessed->allow_bignum;
1256 $bigfloat = $json->decode('2.000000000000000000000000001');
1257 print $json->encode($bigfloat);
1258 # => 2.000000000000000000000000001
1259
1260See to L<MAPPING> aboout the conversion of JSON number.
1261
1262=head2 loose
1263
1264 $json = $json->loose([$enable])
1265
1266The unescaped [\x00-\x1f\x22\x2f\x5c] strings are invalid in JSON strings
1267and the module doesn't allow to C<decode> to these (except for \x2f).
1268If C<$enable> is true (or missing), then C<decode> will accept these
1269unescaped strings.
1270
1271 $json->loose->decode(qq|["abc
1272 def"]|);
1273
1274See to L<JSON::PP/JSON::PP OWN METHODS>.
1275
1276=head2 escape_slash
1277
1278 $json = $json->escape_slash([$enable])
1279
1280According to JSON Grammar, I<slash> (U+002F) is escaped. But by default
1281JSON backend modules encode strings without escaping slash.
1282
1283If C<$enable> is true (or missing), then C<encode> will escape slashes.
1284
1285=head2 indent_length
1286
1287 $json = $json->indent_length($length)
1288
1289With JSON::XS, The indent space length is 3 and cannot be changed.
1290With JSON::PP, it sets the indent space length with the given $length.
1291The default is 3. The acceptable range is 0 to 15.
1292
1293=head2 sort_by
1294
1295 $json = $json->sort_by($function_name)
1296 $json = $json->sort_by($subroutine_ref)
1297
1298If $function_name or $subroutine_ref are set, its sort routine are used.
1299
1300 $js = $pc->sort_by(sub { $JSON::PP::a cmp $JSON::PP::b })->encode($obj);
1301 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1302
1303 $js = $pc->sort_by('own_sort')->encode($obj);
1304 # is($js, q|{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9}|);
1305
1306 sub JSON::PP::own_sort { $JSON::PP::a cmp $JSON::PP::b }
1307
1308As the sorting routine runs in the JSON::PP scope, the given
1309subroutine name and the special variables C<$a>, C<$b> will begin
1310with 'JSON::PP::'.
1311
1312If $integer is set, then the effect is same as C<canonical> on.
1313
1314See to L<JSON::PP/JSON::PP OWN METHODS>.
1315
1316=head1 MAPPING
1317
1318This section is copied from JSON::XS and modified to C<JSON>.
1319JSON::XS and JSON::PP mapping mechanisms are almost equivalent.
1320
1321See to L<JSON::XS/MAPPING>.
1322
1323=head2 JSON -> PERL
1324
1325=over 4
1326
1327=item object
1328
1329A JSON object becomes a reference to a hash in Perl. No ordering of object
1330keys is preserved (JSON does not preserver object key ordering itself).
1331
1332=item array
1333
1334A JSON array becomes a reference to an array in Perl.
1335
1336=item string
1337
1338A JSON string becomes a string scalar in Perl - Unicode codepoints in JSON
1339are represented by the same codepoints in the Perl string, so no manual
1340decoding is necessary.
1341
1342=item number
1343
1344A JSON number becomes either an integer, numeric (floating point) or
1345string scalar in perl, depending on its range and any fractional parts. On
1346the Perl level, there is no difference between those as Perl handles all
1347the conversion details, but an integer may take slightly less memory and
1348might represent more values exactly than floating point numbers.
1349
1350If the number consists of digits only, C<JSON> will try to represent
1351it as an integer value. If that fails, it will try to represent it as
1352a numeric (floating point) value if that is possible without loss of
1353precision. Otherwise it will preserve the number as a string value (in
1354which case you lose roundtripping ability, as the JSON number will be
1355re-encoded toa JSON string).
1356
1357Numbers containing a fractional or exponential part will always be
1358represented as numeric (floating point) values, possibly at a loss of
1359precision (in which case you might lose perfect roundtripping ability, but
1360the JSON number will still be re-encoded as a JSON number).
1361
1362Note that precision is not accuracy - binary floating point values cannot
1363represent most decimal fractions exactly, and when converting from and to
1364floating point, C<JSON> only guarantees precision up to but not including
1365the leats significant bit.
1366
1367If the backend is JSON::PP and C<allow_bignum> is enable, the big integers
1368and the numeric can be optionally converted into L<Math::BigInt> and
1369L<Math::BigFloat> objects.
1370
1371=item true, false
1372
1373These JSON atoms become C<JSON::true> and C<JSON::false>,
1374respectively. They are overloaded to act almost exactly like the numbers
1375C<1> and C<0>. You can check wether a scalar is a JSON boolean by using
1376the C<JSON::is_bool> function.
1377
1378If C<JSON::true> and C<JSON::false> are used as strings or compared as strings,
1379they represent as C<true> and C<false> respectively.
1380
1381 print JSON::true . "\n";
1382 => true
1383 print JSON::true + 1;
1384 => 1
1385
1386 ok(JSON::true eq 'true');
1387 ok(JSON::true eq '1');
1388 ok(JSON::true == 1);
1389
1390C<JSON> will install these missing overloading features to the backend modules.
1391
1392
1393=item null
1394
1395A JSON null atom becomes C<undef> in Perl.
1396
1397C<JSON::null> returns C<unddef>.
1398
1399=back
1400
1401
1402=head2 PERL -> JSON
1403
1404The mapping from Perl to JSON is slightly more difficult, as Perl is a
1405truly typeless language, so we can only guess which JSON type is meant by
1406a Perl value.
1407
1408=over 4
1409
1410=item hash references
1411
1412Perl hash references become JSON objects. As there is no inherent ordering
1413in hash keys (or JSON objects), they will usually be encoded in a
1414pseudo-random order that can change between runs of the same program but
1415stays generally the same within a single run of a program. C<JSON>
1416optionally sort the hash keys (determined by the I<canonical> flag), so
1417the same datastructure will serialise to the same JSON text (given same
1418settings and version of JSON::XS), but this incurs a runtime overhead
1419and is only rarely useful, e.g. when you want to compare some JSON text
1420against another for equality.
1421
1422In future, the ordered object feature will be added to JSON::PP using C<tie> mechanism.
1423
1424
1425=item array references
1426
1427Perl array references become JSON arrays.
1428
1429=item other references
1430
1431Other unblessed references are generally not allowed and will cause an
1432exception to be thrown, except for references to the integers C<0> and
1433C<1>, which get turned into C<false> and C<true> atoms in JSON. You can
1434also use C<JSON::false> and C<JSON::true> to improve readability.
1435
1436 to_json [\0,JSON::true] # yields [false,true]
1437
1438=item JSON::true, JSON::false, JSON::null
1439
1440These special values become JSON true and JSON false values,
1441respectively. You can also use C<\1> and C<\0> directly if you want.
1442
1443JSON::null returns C<undef>.
1444
1445=item blessed objects
1446
1447Blessed objects are not directly representable in JSON. See the
1448C<allow_blessed> and C<convert_blessed> methods on various options on
1449how to deal with this: basically, you can choose between throwing an
1450exception, encoding the reference as if it weren't blessed, or provide
1451your own serialiser method.
1452
1453With C<convert_blessed_universally> mode, C<encode> converts blessed
1454hash references or blessed array references (contains other blessed references)
1455into JSON members and arrays.
1456
1457 use JSON -convert_blessed_universally;
1458 JSON->new->allow_blessed->convert_blessed->encode( $blessed_object );
1459
1460See to L<convert_blessed>.
1461
1462=item simple scalars
1463
1464Simple Perl scalars (any scalar that is not a reference) are the most
1465difficult objects to encode: JSON::XS and JSON::PP will encode undefined scalars as
1466JSON C<null> values, scalars that have last been used in a string context
1467before encoding as JSON strings, and anything else as number value:
1468
1469 # dump as number
1470 encode_json [2] # yields [2]
1471 encode_json [-3.0e17] # yields [-3e+17]
1472 my $value = 5; encode_json [$value] # yields [5]
1473
1474 # used as string, so dump as string
1475 print $value;
1476 encode_json [$value] # yields ["5"]
1477
1478 # undef becomes null
1479 encode_json [undef] # yields [null]
1480
1481You can force the type to be a string by stringifying it:
1482
1483 my $x = 3.1; # some variable containing a number
1484 "$x"; # stringified
1485 $x .= ""; # another, more awkward way to stringify
1486 print $x; # perl does it for you, too, quite often
1487
1488You can force the type to be a number by numifying it:
1489
1490 my $x = "3"; # some variable containing a string
1491 $x += 0; # numify it, ensuring it will be dumped as a number
1492 $x *= 1; # same thing, the choise is yours.
1493
1494You can not currently force the type in other, less obscure, ways.
1495
1496Note that numerical precision has the same meaning as under Perl (so
1497binary to decimal conversion follows the same rules as in Perl, which
1498can differ to other languages). Also, your perl interpreter might expose
1499extensions to the floating point numbers of your platform, such as
1500infinities or NaN's - these cannot be represented in JSON, and it is an
1501error to pass those in.
1502
1503=item Big Number
1504
1505If the backend is JSON::PP and C<allow_bignum> is enable,
1506C<encode> converts C<Math::BigInt> objects and C<Math::BigFloat>
1507objects into JSON numbers.
1508
1509
1510=back
1511
1512=head1 JSON and ECMAscript
1513
1514See to L<JSON::XS/JSON and ECMAscript>.
1515
1516=head1 JSON and YAML
1517
1518JSON is not a subset of YAML.
1519See to L<JSON::XS/JSON and YAML>.
1520
1521
1522=head1 BACKEND MODULE DECISION
1523
1524When you use C<JSON>, C<JSON> tries to C<use> JSON::XS. If this call failed, it will
1525C<uses> JSON::PP. The required JSON::XS version is I<2.2> or later.
1526
1527The C<JSON> constructor method returns an object inherited from the backend module,
1528and JSON::XS object is a blessed scaler reference while JSON::PP is a blessed hash
1529reference.
1530
1531So, your program should not depend on the backend module, especially
1532returned objects should not be modified.
1533
1534 my $json = JSON->new; # XS or PP?
1535 $json->{stash} = 'this is xs object'; # this code may raise an error!
1536
1537To check the backend module, there are some methods - C<backend>, C<is_pp> and C<is_xs>.
1538
1539 JSON->backend; # 'JSON::XS' or 'JSON::PP'
1540
1541 JSON->backend->is_pp: # 0 or 1
1542
1543 JSON->backend->is_xs: # 1 or 0
1544
1545 $json->is_xs; # 1 or 0
1546
1547 $json->is_pp; # 0 or 1
1548
1549
1550If you set an enviornment variable C<PERL_JSON_BACKEND>, The calling action will be changed.
1551
1552=over
1553
1554=item PERL_JSON_BACKEND = 0 or PERL_JSON_BACKEND = 'JSON::PP'
1555
1556Always use JSON::PP
1557
1558=item PERL_JSON_BACKEND == 1 or PERL_JSON_BACKEND = 'JSON::XS,JSON::PP'
1559
1560(The default) Use compiled JSON::XS if it is properly compiled & installed,
1561otherwise use JSON::PP.
1562
1563=item PERL_JSON_BACKEND == 2 or PERL_JSON_BACKEND = 'JSON::XS'
1564
1565Always use compiled JSON::XS, die if it isn't properly compiled & installed.
1566
1567=item PERL_JSON_BACKEND = 'JSON::backportPP'
1568
1569Always use JSON::backportPP.
1570JSON::backportPP is JSON::PP back port module.
1571C<JSON> includs JSON::backportPP instead of JSON::PP.
1572
1573=back
1574
1575These ideas come from L<DBI::PurePerl> mechanism.
1576
1577example:
1578
1579 BEGIN { $ENV{PERL_JSON_BACKEND} = 'JSON::PP' }
1580 use JSON; # always uses JSON::PP
1581
1582In future, it may be able to specify another module.
1583
1584=head1 USE PP FEATURES EVEN THOUGH XS BACKEND
1585
1586Many methods are available with either JSON::XS or JSON::PP and
1587when the backend module is JSON::XS, if any JSON::PP specific (i.e. JSON::XS unspported)
1588method is called, it will C<warn> and be noop.
1589
1590But If you C<use> C<JSON> passing the optional string C<-support_by_pp>,
1591it makes a part of those unupported methods available.
1592This feature is achieved by using JSON::PP in C<de/encode>.
1593
1594 BEGIN { $ENV{PERL_JSON_BACKEND} = 2 } # with JSON::XS
1595 use JSON -support_by_pp;
1596 my $json = new JSON;
1597 $json->allow_nonref->escape_slash->encode("/");
1598
1599At this time, the returned object is a C<JSON::Backend::XS::Supportable>
1600object (re-blessed XS object), and by checking JSON::XS unsupported flags
1601in de/encoding, can support some unsupported methods - C<loose>, C<allow_bignum>,
1602C<allow_barekey>, C<allow_singlequote>, C<escape_slash> and C<indent_length>.
1603
1604When any unsupported methods are not enable, C<XS de/encode> will be
1605used as is. The switch is achieved by changing the symbolic tables.
1606
1607C<-support_by_pp> is effective only when the backend module is JSON::XS
1608and it makes the de/encoding speed down a bit.
1609
1610See to L<JSON::PP SUPPORT METHODS>.
1611
1612=head1 INCOMPATIBLE CHANGES TO OLD VERSION
1613
1614There are big incompatibility between new version (2.00) and old (1.xx).
1615If you use old C<JSON> 1.xx in your code, please check it.
1616
1617See to L<Transition ways from 1.xx to 2.xx.>
1618
1619=over
1620
1621=item jsonToObj and objToJson are obsoleted.
1622
1623Non Perl-style name C<jsonToObj> and C<objToJson> are obsoleted
1624(but not yet deleted from the source).
1625If you use these functions in your code, please replace them
1626with C<from_json> and C<to_json>.
1627
1628
1629=item Global variables are no longer available.
1630
1631C<JSON> class variables - C<$JSON::AUTOCONVERT>, C<$JSON::BareKey>, etc...
1632- are not available any longer.
1633Instead, various features can be used through object methods.
1634
1635
1636=item Package JSON::Converter and JSON::Parser are deleted.
1637
1638Now C<JSON> bundles with JSON::PP which can handle JSON more properly than them.
1639
1640=item Package JSON::NotString is deleted.
1641
1642There was C<JSON::NotString> class which represents JSON value C<true>, C<false>, C<null>
1643and numbers. It was deleted and replaced by C<JSON::Boolean>.
1644
1645C<JSON::Boolean> represents C<true> and C<false>.
1646
1647C<JSON::Boolean> does not represent C<null>.
1648
1649C<JSON::null> returns C<undef>.
1650
1651C<JSON> makes L<JSON::XS::Boolean> and L<JSON::PP::Boolean> is-a relation
1652to L<JSON::Boolean>.
1653
1654=item function JSON::Number is obsoleted.
1655
1656C<JSON::Number> is now needless because JSON::XS and JSON::PP have
1657round-trip integrity.
1658
1659=item JSONRPC modules are deleted.
1660
1661Perl implementation of JSON-RPC protocol - C<JSONRPC >, C<JSONRPC::Transport::HTTP>
1662and C<Apache::JSONRPC > are deleted in this distribution.
1663Instead of them, there is L<JSON::RPC> which supports JSON-RPC protocol version 1.1.
1664
1665=back
1666
1667=head2 Transition ways from 1.xx to 2.xx.
1668
1669You should set C<suport_by_pp> mode firstly, because
1670it is always successful for the below codes even with JSON::XS.
1671
1672 use JSON -support_by_pp;
1673
1674=over
1675
1676=item Exported jsonToObj (simple)
1677
1678 from_json($json_text);
1679
1680=item Exported objToJson (simple)
1681
1682 to_json($perl_scalar);
1683
1684=item Exported jsonToObj (advanced)
1685
1686 $flags = {allow_barekey => 1, allow_singlequote => 1};
1687 from_json($json_text, $flags);
1688
1689equivalent to:
1690
1691 $JSON::BareKey = 1;
1692 $JSON::QuotApos = 1;
1693 jsonToObj($json_text);
1694
1695=item Exported objToJson (advanced)
1696
1697 $flags = {allow_blessed => 1, allow_barekey => 1};
1698 to_json($perl_scalar, $flags);
1699
1700equivalent to:
1701
1702 $JSON::BareKey = 1;
1703 objToJson($perl_scalar);
1704
1705=item jsonToObj as object method
1706
1707 $json->decode($json_text);
1708
1709=item objToJson as object method
1710
1711 $json->encode($perl_scalar);
1712
1713=item new method with parameters
1714
1715The C<new> method in 2.x takes any parameters no longer.
1716You can set parameters instead;
1717
1718 $json = JSON->new->pretty;
1719
1720=item $JSON::Pretty, $JSON::Indent, $JSON::Delimiter
1721
1722If C<indent> is enable, that means C<$JSON::Pretty> flag set. And
1723C<$JSON::Delimiter> was substituted by C<space_before> and C<space_after>.
1724In conclusion:
1725
1726 $json->indent->space_before->space_after;
1727
1728Equivalent to:
1729
1730 $json->pretty;
1731
1732To change indent length, use C<indent_length>.
1733
1734(Only with JSON::PP, if C<-support_by_pp> is not used.)
1735
1736 $json->pretty->indent_length(2)->encode($perl_scalar);
1737
1738=item $JSON::BareKey
1739
1740(Only with JSON::PP, if C<-support_by_pp> is not used.)
1741
1742 $json->allow_barekey->decode($json_text)
1743
1744=item $JSON::ConvBlessed
1745
1746use C<-convert_blessed_universally>. See to L<convert_blessed>.
1747
1748=item $JSON::QuotApos
1749
1750(Only with JSON::PP, if C<-support_by_pp> is not used.)
1751
1752 $json->allow_singlequote->decode($json_text)
1753
1754=item $JSON::SingleQuote
1755
1756Disable. C<JSON> does not make such a invalid JSON string any longer.
1757
1758=item $JSON::KeySort
1759
1760 $json->canonical->encode($perl_scalar)
1761
1762This is the ascii sort.
1763
1764If you want to use with your own sort routine, check the C<sort_by> method.
1765
1766(Only with JSON::PP, even if C<-support_by_pp> is used currently.)
1767
1768 $json->sort_by($sort_routine_ref)->encode($perl_scalar)
1769
1770 $json->sort_by(sub { $JSON::PP::a <=> $JSON::PP::b })->encode($perl_scalar)
1771
1772Can't access C<$a> and C<$b> but C<$JSON::PP::a> and C<$JSON::PP::b>.
1773
1774=item $JSON::SkipInvalid
1775
1776 $json->allow_unknown
1777
1778=item $JSON::AUTOCONVERT
1779
1780Needless. C<JSON> backend modules have the round-trip integrity.
1781
1782=item $JSON::UTF8
1783
1784Needless because C<JSON> (JSON::XS/JSON::PP) sets
1785the UTF8 flag on properly.
1786
1787 # With UTF8-flagged strings
1788
1789 $json->allow_nonref;
1790 $str = chr(1000); # UTF8-flagged
1791
1792 $json_text = $json->utf8(0)->encode($str);
1793 utf8::is_utf8($json_text);
1794 # true
1795 $json_text = $json->utf8(1)->encode($str);
1796 utf8::is_utf8($json_text);
1797 # false
1798
1799 $str = '"' . chr(1000) . '"'; # UTF8-flagged
1800
1801 $perl_scalar = $json->utf8(0)->decode($str);
1802 utf8::is_utf8($perl_scalar);
1803 # true
1804 $perl_scalar = $json->utf8(1)->decode($str);
1805 # died because of 'Wide character in subroutine'
1806
1807See to L<JSON::XS/A FEW NOTES ON UNICODE AND PERL>.
1808
1809=item $JSON::UnMapping
1810
1811Disable. See to L<MAPPING>.
1812
1813=item $JSON::SelfConvert
1814
1815This option was deleted.
1816Instead of it, if a givien blessed object has the C<TO_JSON> method,
1817C<TO_JSON> will be executed with C<convert_blessed>.
1818
1819 $json->convert_blessed->encode($bleesed_hashref_or_arrayref)
1820 # if need, call allow_blessed
1821
1822Note that it was C<toJson> in old version, but now not C<toJson> but C<TO_JSON>.
1823
1824=back
1825
1826=head1 TODO
1827
1828=over
1829
1830=item example programs
1831
1832=back
1833
1834=head1 THREADS
1835
1836No test with JSON::PP. If with JSON::XS, See to L<JSON::XS/THREADS>.
1837
1838
1839=head1 BUGS
1840
1841Please report bugs relevant to C<JSON> to E<lt>makamaka[at]cpan.orgE<gt>.
1842
1843
1844=head1 SEE ALSO
1845
1846Most of the document is copied and modified from JSON::XS doc.
1847
1848L<JSON::XS>, L<JSON::PP>
1849
1850C<RFC4627>(L<http://www.ietf.org/rfc/rfc4627.txt>)
1851
1852=head1 AUTHOR
1853
1854Makamaka Hannyaharamitu, E<lt>makamaka[at]cpan.orgE<gt>
1855
1856JSON::XS was written by Marc Lehmann <schmorp[at]schmorp.de>
1857
1858The relese of this new version owes to the courtesy of Marc Lehmann.
1859
1860
1861=head1 COPYRIGHT AND LICENSE
1862
1863Copyright 2005-2011 by Makamaka Hannyaharamitu
1864
1865This library is free software; you can redistribute it and/or modify
1866it under the same terms as Perl itself.
1867
1868=cut
1869
1870
1871;